package com.jyw.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.Address;
import com.jyw.pojo.EventBusTypes;

import java.io.IOException;
import java.util.Calendar;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/1
 */

public class OrderAddActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout layoutTime, layoutAddress;
    private Calendar sCalendar;
    private TextView btnYuyue, tvTime, tvAddress;
    private EditText editMark;

    public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();

    private String selectedOrderId;
    private String lat;
    private String longt;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_order_add);

        layoutTime = (LinearLayout) findViewById(R.id.layout_time);
        layoutAddress = (LinearLayout) findViewById(R.id.layout_address);
        btnYuyue = (TextView) findViewById(R.id.btn_yuyue);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        editMark = (EditText) findViewById(R.id.edit_mark);
        layoutTime.setOnClickListener(this);
        layoutAddress.setOnClickListener(this);
        btnYuyue.setOnClickListener(this);

        findViewById(R.id.iv_back).setOnClickListener(this);

        loadAddressDefault();

        mLocationClient = new LocationClient(OrderAddActivity.this);
        mLocationClient.registerLocationListener(myListener);

        setLocationOption();
        mLocationClient.start();
    }

    private class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            lat = location.getLatitude() + "";
            longt = location.getLongitude() + "";
            mLocationClient.stop();
        }
    }


    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); //打开gps
        option.setServiceName("com.baidu.location.service_v2.9");
        /*option.setPoiExtraInfo(true);*/
        option.setAddrType("all");
        option.setPriority(LocationClientOption.NetWorkFirst);
        option.setPriority(LocationClientOption.GpsFirst);       //gps
        /*option.setPoiNumber(10);*/
        option.disableCache(true);
        mLocationClient.setLocOption(option);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_time:
                startActivity(new Intent(OrderAddActivity.this, TimePicker.class));
                break;
            case R.id.layout_address:
                startActivity(new Intent(OrderAddActivity.this, AddressesActivity.class));
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.btn_yuyue:
                if (getPrefs().getString("phone", "").equals("")) {
                    startActivity(new Intent(OrderAddActivity.this, LoginActivity.class));
                } else {
                    yuyueGo();
                }
                break;
        }
    }

    private void yuyueGo() {
        if (tvTime.getText().toString().equals("")) {
            Toast.makeText(OrderAddActivity.this, "请选择日期和时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (lat == null || lat.equals("")) {
            Toast.makeText(OrderAddActivity.this, "定位信息失败", Toast.LENGTH_SHORT).show();
            return;
        }
        final Request request = new Request.Builder().
                url(Server.CREATE_ORDER + "?phone_data=" + getPrefs().getString("phone", "")
                        + "&address_data=" + selectedOrderId
                        + "&time_data=" + tvTime.getText().toString()
                        + "&mark_data=" + editMark.getText().toString()
                        + "&class_data=" + getIntent().getStringExtra("class_data")
                        + "&lat=" + lat
                        + "&longt=" + longt
                ).build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderAddActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String id = response.body().string();
                if (id.equals("-5")) {
                    OkHttpManager.backgroundThreadShortToast(OrderAddActivity.this, "您的位置不在服务范围内");
                } else {
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);
                            Intent intent = new Intent(OrderAddActivity.this, OrderActivity.class);
                            intent.putExtra("order_id", id);
                            startActivity(intent);
                            OrderAddActivity.this.finish();
                        }
                    }.execute();
                }
            }
        });
    }

    private void loadAddressDefault() {
        final Request request = new Request.Builder().
                url(Server.GET_ADDRESS_DEFAUT + "?phone_data=" + getPrefs().getString("phone", "")
                ).build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrderAddActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final Address address = new Gson().fromJson(response.body().string(), Address.class);
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        tvAddress.setText(address.getCity() + " " + address.getCircle() + " " + address.getDetail());
                        selectedOrderId = address.getId();
                    }
                }.execute();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(EventBusTypes.Base type) {
        if (type instanceof EventBusTypes.DateTimeSelected) {
            tvTime.setText(((EventBusTypes.DateTimeSelected) type).timeSelected);
        } else if (type instanceof EventBusTypes.AddressSelected) {
            Address address = ((EventBusTypes.AddressSelected) type).address;
            selectedOrderId = address.getId();
            tvAddress.setText(address.getCity() + " " + address.getCircle() + " " + address.getDetail());
        }

    }
}
